package com.piece.module.flowable.service;

import com.piece.core.framework.enums.StatusType;
import com.piece.core.framework.util.object.ObjectUtil;
import com.piece.core.jpa.repository.BaseService;
import com.piece.module.flowable.model.WfForm;
import com.piece.module.flowable.repository.WfDeployFormRepository;
import com.piece.module.flowable.repository.WfFormRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.List;

@Service
@Transactional
public class WfFormService extends BaseService<WfForm, Long> {

    @Autowired
    private WfFormRepository wfFormRepository;

    @Autowired
    private WfDeployFormRepository wfDeployFormRepository;

    @PostConstruct
    public void initRepository() {
        setRepository(wfFormRepository);
    }

    public WfForm findByDeploymentId(String deploymentId) {
        String hql = "select f.* from `wf_form` f " +
                " left join `wf_deploy_form` d on d.form_key = f.form_id " +
                " where d.deploy_id = ?0";
        List<WfForm> result = wfFormRepository.findBySql(hql, new Object[]{deploymentId});
        return ObjectUtil.isEmpty(result) ? null : result.get(0);
    }

    /**
     * 校验表单名称是否唯一
     *
     * @param formName 表单名称
     * @return true: 通过 false: 重复
     */
    public boolean checkFormNameUnique(Long formId, String formName) {
        String hql = "from WfForm where formName = ?0 and status = ?1";
        Object[] params = new Object[]{formName, StatusType.NORMAL.getCode()};
        if (null != formId) {
            hql = "from WfForm where formId != ?0 and formName = ?1 and status = ?2 ";
            params = new Object[]{formId, formName, StatusType.NORMAL.getCode()};
        }
        long count = wfFormRepository.count(hql, params, true);
        return count <= 0;
    }
}
